/**
 * @file models/app.js
 *  login
 * @author
 */

import api from '../api';
import { routerRedux } from 'dva/router';
import { dealUrl } from '../utils';

export default {
	namespace: 'login',
	state: {
		// 登录用户的信息
		userInfo: {},
	},
	subscriptions:{
		setup({dispatch,history}) {
			history.listen(({pathname,query}) => {
				// if( pathname === '/login' ){
					// dispatch({
					// 	type: 'logout',
					// })
				// }
			})
		}
	},
	effects: {
		* queryUser({
			payload,
		}, { call, put }) {
			const data = yield call(api.queryUser, payload);
			if (data.msg === 'OK') {
				yield put({
					type: 'querySuccess',
					payload: {data},
				});
				// yield put(routerRedux.push('/'));
			}else{
				yield put(routerRedux.push('/login'));
			}
		},
		* login({ payload: { userName, password } }, { call, put }) {
			const query = {
				username: userName,
				password,
			}
			const response = yield call(api.login, query);
			if (response.code == '0' && response.msg == 'OK') {
				// console.log('0-0-0-0-0-',location)
				// yield put({
				// 	type: 'queryUser',
				// });
				// window.location.reload()
				if(localStorage.from!=='/login'){
					yield put(routerRedux.push(localStorage.from||'/welcomehtzq'))
					localStorage.removeItem('from')
				}

				// yield put(routerRedux.push(dealUrl.uriQuery('from') || '/'));
			} else {
				throw '请输入正确的用户名或密码';
			}
		},
		* logout({ payload }, { call, put }) {
			// window.location.href = `${location.origin}`;
			yield call(api.logout);
			yield put({
				type:"initData",
				payload:{
					userInfo:{}
				}
			})
			// yield put(routerRedux.push('/login'));
			// window.location.reload()
		},
		*loginout({},{call,put}){
			yield put(routerRedux.push('/login'));
			window.location.reload()
		}
	},
	reducers: {
		initData(state,{payload}){
			return{
				...state,
				...payload
			}
		},
		querySuccess(state, action) {
			const { payload: { data } } = action;
			const { userInfo } = data.data;
			return {
				...state,
				userInfo: data.data,
			};
		},
	},
};
